#pragma once
#include <iostream>
#include <stdio.h>
#include <set>
class Command
{
public:
    Command()
    {
        _safe_command.insert("ls -l"); // 使用不了在Ubuntu下
        _safe_command.insert("ll");    // 这个也是
        _safe_command.insert("pwd");
    }
    std::string Execute(const std::string &cmdstr)
    {
        auto it = _safe_command.find(cmdstr);
        if (it == _safe_command.end())
        {
            return "not find this command";
        }
        // 1.打开管道 2. dup2(pipefd,1)重定向  3. exec* 程序替换
        FILE *pipefile = popen(cmdstr.c_str(), "r");
        if (pipefile == nullptr)
        {
            return "failed to run command";
        }
        char buffer[1024];
        std::string result;
        while (fgets(buffer, sizeof(buffer), pipefile))
        {
            result += buffer;
        }
        pclose(pipefile);
        return result;
    }
    void Helper()
    {
        std::cout << "可用命令: ";
        for (auto &e : _safe_command)
        {
            std::cout << e << " ";
        }
        std::cout << std::endl;
    }

private:
    std::set<std::string> _safe_command;
};